package org.jeecg.config.wlhy;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.enums.BaiduErrorCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static org.jeecg.config.wlhy.OkHttp.HTTP_CLIENT;

@Configuration
@Slf4j
public class QuickVisionClient {

    @Value("${quick_vision_ai.accessKey}")
    private String accessKey;

    @Value("${quick_vision_ai.accessSecret}")
    private String accessSecret;


    @Resource
    StringRedisTemplate stringRedisTemplate;

    /**
     *
     * @param bankcard
     * @param realName
     * @param idCard
     * @param mobile
     * @return
     * {
     *     "code": 10000,
     *     "status": 200,
     *     "message": "验证通过",
     *     "serialNo": "380497356832899072"
     * }
     * @throws IOException
     */
    public Boolean bankNameIdCardMobile(
            String bankcard,
            String realName,
            String idCard,
            String mobile) throws IOException {
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        formBodyBuilder.add("token", getAccessToken());
        formBodyBuilder.add("bankcard", bankcard);
        formBodyBuilder.add("realName", realName);
        formBodyBuilder.add("idCard", idCard);
        formBodyBuilder.add("mobile", mobile);

        Request request = new Request.Builder()
                .url("https://ai.inspirvision.cn/s/api/ocr/cloudCode/bankNameIdCardMobile")
                .method("POST", formBodyBuilder.build())
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        JSONObject jsonObject = JSONObject.parseObject(response.body().string());
        if (jsonObject.getInteger("status").equals(200)) {
            return true;
        }

        throw new  RuntimeException(jsonObject.getString("message"));
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    String getAccessToken() throws IOException {
        String accessToken = stringRedisTemplate.opsForValue().get("QuickVision");
        if (StringUtils.isNotBlank(accessToken)) {
            return accessToken;
        }

        HttpUrl.Builder urlBuilder = HttpUrl.parse("https://ai.inspirvision.cn/s/api/getAccessToken").newBuilder();
        urlBuilder.addQueryParameter("accessKey", accessKey);
        urlBuilder.addQueryParameter("accessSecret", accessSecret);
        String url = urlBuilder.build().toString();

        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        JSONObject jsonObject = JSONObject.parseObject(response.body().string());
        if (!jsonObject.getInteger("status").equals(200)) {
            throw new RuntimeException(jsonObject.getString("message"));
        }

        JSONObject data = jsonObject.getJSONObject("data");
        accessToken = data.getString("access_token");
        Integer expireIn = data.getInteger("expires_in");
        stringRedisTemplate.opsForValue().set("QuickVision", accessToken, expireIn, TimeUnit.SECONDS);
        return accessToken;
    }

}
